package com.laisheng.interview.controller;

import com.laisheng.interview.model.DevelopmentExercises;
import com.laisheng.interview.service.ExercisesService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/exercises")
public class ExercisesController {
    @Autowired
    private ExercisesService exercisesService;

    @PostMapping("/submit")
    public Map<String, Object> submitExercises(@RequestBody DevelopmentExercises exercises, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 优先使用请求体中的accountingId，如果没有则从session获取
            if (exercises.getAccountingId() == null) {
                Long accountingInfoId = (Long) request.getSession().getAttribute("accountingId");
                exercises.setAccountingId(accountingInfoId);
            }
            
            if (exercises.getAccountingId() == null) {
                response.put("success", false);
                response.put("message", "缺少accountingId参数");
                return response;
            }
            
            System.out.println("提交练习题答案: " + exercises);
            exercisesService.save(exercises);
            response.put("success", true);
            response.put("message", "答案提交成功");
        } catch (Exception e) {
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "提交失败: " + e.getMessage());
        }
        return response;
    }
}